package xyz.fefine;

import java.util.List;

/**
 * Created by feng_ on 2016/9/8.
 *
 */
public class PrimaryExpr extends ASTList{

    public PrimaryExpr(List<ASTree> list) {
        super(list);
    }

    public static ASTree create(List<ASTree> c) {
        return c.size() == 1 ? c.get(0) : new PrimaryExpr(c);
    }

    /**
     * 调用的方法名称
     * @return
     */
    public String funName(){
        return ((Name)child(0)).name();
    }

    public ASTree operand() {
        //里面是name,但是name.eval()返回的是个函数
        return child(0);
    }

    public Postfix postfix(int nest) {
        return (Postfix) child(numChildren() - nest - 1);
    }

    public boolean hasNextPostfix(int nest) {
        return numChildren() - nest > 1 ;
    }

    /**
     * 调用的方法参数
     * @return
     */
    public Arguments args(){
        return (Arguments) child(1);
    }

    @Override
    public Object eval(Enviorment enviorment) {
        //递归调用 || 循环调用  实现闭包

/*        //循环
        Object res = operand().eval(enviorment);  //函数eval会更新env中的同名的函数对象(Function)
        for (int i = 1; i < numChildren(); i++) {
            res = postfix(i).eval(enviorment, res);
        }*/

        //递归
        return evalHelper(enviorment,0);

    }

    public Object evalHelper(Enviorment env, int nest) {
        if (hasNextPostfix(nest)) {
            Object res = evalHelper(env, nest + 1);
            return (postfix(nest)).eval(env,res);
        } else {
            return operand().eval(env);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(" (");
        for (ASTree asTree : children) {

            sb.append(asTree.toString());
        }
        sb.append(") ");
        return sb.toString();
    }
}
